package dyyx.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class SimpleTelnetClient implements Closeable {

	private final Socket socket;
	private final InputStream in;
	private final OutputStream out;
	
	private final BufferedReader br;
	private final BufferedWriter bw;
	
	public static final int TIMEOUT = 10000; 


	public SimpleTelnetClient(String ip, int port) throws Exception {
		
		
		socket = new Socket(ip,port);
		socket.setTcpNoDelay(true);
		// milliseconds
		socket.setSoTimeout(TIMEOUT);
		
		

		in = socket.getInputStream();
		out = socket.getOutputStream();
		
		
		br = new BufferedReader(new InputStreamReader(in));
				
		bw = new BufferedWriter(new OutputStreamWriter(out));


	}

	

	private void write(String value) throws Exception {
		bw.write(value);
		bw.newLine();
		bw.flush();
	}

	public String sendCommand(String command) throws Exception {
		write(command);
		return read();
	}

	private String read() throws Exception {
		return br.readLine();
	}

	public void close() throws IOException{
		if(socket==null){
			return;
		}
		socket.close();
		CommUtil.close(br);
		CommUtil.close(bw);
		CommUtil.close(in);
		CommUtil.close(out);

	}

}
